import React, { useState, useEffect } from 'react';
import { Layout, Menu, Tabs, Grid, Result, Button } from 'antd';
import { useSelector } from 'react-redux';
import { RootState } from '@/store/rootReducer';
import { 
  HomeOutlined, 
  UserOutlined, 
  BookOutlined,
  FileTextOutlined,
  LikeOutlined,
  CommentOutlined,
  ScheduleOutlined,
  ProfileOutlined,
  MenuFoldOutlined,
  MenuUnfoldOutlined,
  PictureOutlined
} from '@ant-design/icons';
import { useNavigate, useLocation, Outlet, Navigate } from 'react-router-dom';
import type { TabsProps } from 'antd';

const { Header, Sider, Content } = Layout;
const { useBreakpoint } = Grid;

interface TabItem {
  key: string;
  label: string;
  path: string;
}

interface MenuItem {
  key: string;
  icon?: React.ReactNode;
  label: string;
  path?: string;
  children?: MenuItem[];
}

export default function Admin() {
  const navigate = useNavigate();
  const location = useLocation();
  const loginUser = useSelector((state: RootState) => state.loginUser);
  const [collapsed, setCollapsed] = useState(false);
  const [activeTab, setActiveTab] = useState<string>('home');
  const [openTabs, setOpenTabs] = useState<TabItem[]>([
    { key: 'home', label: '管理首页', path: '/admin/home' }
  ]);
  
  const screens = useBreakpoint();

  // 权限检查
  if (!loginUser || loginUser.userRole !== 'admin') {
    return <Navigate to="/" replace />;
  }

  const menuItems: MenuItem[] = [
    { key: 'home', icon: <HomeOutlined />, label: '管理首页', path: '/admin/home' },
    { key: 'carousel', icon: <PictureOutlined />, label: '轮播图管理', path: '/admin/carousel' },
    { key: 'users', icon: <UserOutlined />, label: '用户管理', path: '/admin/users' },
    {
      key: 'books',
      icon: <BookOutlined />,
      label: '图书管理',
      children: [
        { key: 'book-categories', label: '图书分类', path: '/admin/books/categories' },
        { key: 'book-management', label: '图书管理', path: '/admin/books/management' },
      ]
    },
    {
      key: 'posts',
      icon: <FileTextOutlined />,
      label: '帖子管理',
      children: [
        { key: 'post-categories', label: '帖子分类', path: '/admin/posts/categories' },
        { key: 'post-management', label: '帖子管理', path: '/admin/posts/management' },
        { key: 'post-tags', label: '帖子标签', path: '/admin/posts/tags' },
      ]
    },
    { key: 'comments', icon: <CommentOutlined />, label: '评论管理', path: '/admin/comments' },
    { key: 'seats', icon: <ScheduleOutlined />, label: '预约座位管理', path: '/admin/seats' },
    { key: 'borrowing', icon: <ProfileOutlined />, label: '借阅书籍管理', path: '/admin/borrowing' },
  ];

  const handleMenuClick = ({ key }: { key: string }) => {
    const findMenuItem = (items: MenuItem[]): MenuItem | null => {
      for (const item of items) {
        if (item.key === key) return item;
        if (item.children) {
          const found = item.children.find(child => child.key === key);
          if (found) return found;
        }
      }
      return null;
    };

    const menuItem = findMenuItem(menuItems);
    if (!menuItem || !menuItem.path) return;

    if (!openTabs.find(tab => tab.key === key)) {
      setOpenTabs([...openTabs, { 
        key: menuItem.key,
        label: menuItem.label,
        path: menuItem.path
      }]);
    }
    setActiveTab(key);
    navigate(menuItem.path);
  };

  const handleTabChange = (key: string) => {
    setActiveTab(key);
    const tab = openTabs.find(tab => tab.key === key);
    if (tab) {
      navigate(tab.path);
    }
  };

  const handleTabEdit: TabsProps['onEdit'] = (targetKey, action) => {
    if (action === 'remove' && typeof targetKey === 'string') {
      const newTabs = openTabs.filter(tab => tab.key !== targetKey);
      setOpenTabs(newTabs);
      
      if (targetKey === activeTab) {
        const firstTab = newTabs[0];
        if (firstTab) {
          setActiveTab(firstTab.key);
          navigate(firstTab.path);
        }
      }
    }
  };

  // 如果屏幕小于 xl 尺寸，显示提示信息
  if (!screens.xl) {
    return (
      <Result
        status="warning"
        title="请使用PC端打开此页面"
        subTitle="为了更好的使用体验，请使用更大尺寸的屏幕访问管理后台"
        extra={
          <Button type="primary" onClick={() => navigate('/')}>
            返回首页
          </Button>
        }
      />
    );
  }

  return (
    <Layout className="h-screen">
      <Sider 
        width={200} 
        theme="dark" 
        collapsible 
        collapsed={collapsed}
        onCollapse={(value) => setCollapsed(value)}
        trigger={null}
      >
        <div style={{ 
          height: 32, 
          margin: 16, 
          background: 'rgba(255, 255, 255, 0.2)',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          color: '#fff'
        }}>
          {!collapsed ? '星轨-图书借阅系统' : '图书'}
        </div>
        <Menu
          theme="dark"
          mode="inline"
          selectedKeys={[activeTab]}
          onClick={handleMenuClick}
          items={menuItems}
        />
      </Sider>
      <Layout>
        <Header className="p-0 bg-white">
        <div className="flex justify-between items-center">
        <Button
            type="text"
            icon={collapsed ? <MenuUnfoldOutlined /> : <MenuFoldOutlined />}
            onClick={() => setCollapsed(!collapsed)}
            className="w-16 h-16 text-base"
          />
          <Button
            type="primary"
            className="mr-4"
            onClick={() => navigate('/')}
          >
            返回首页
          </Button>
        </div>
        </Header>
        <Content className="flex flex-col">
          <Tabs
            type="editable-card"
            onChange={handleTabChange}
            activeKey={activeTab}
            onEdit={handleTabEdit}
            items={openTabs.map(tab => ({
              key: tab.key,
              label: tab.label,
              closable: tab.key !== 'home',
            }))}
            className="px-4 pt-4"
          />
          <div className="flex-1 p-4 overflow-auto scrollbar-custom">
            <Outlet />
          </div>
        </Content>
      </Layout>
    </Layout>
  );
}